package cn.hpclub.server.model;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@TableBind(tableName = "localized_config")
public class LocalizedConfig extends Model<LocalizedConfig> implements Serializable{

    public static final LocalizedConfig dao              = new LocalizedConfig();
    public static final String LOCALIZED = "localized";

    public static final int BUSINESS_TARIFF = 0;//资费小类的类型为0
    public static final int TYPE_PACKAGE_XHRW = 1003; //1003,与businessauthconfig保持一致
//    public static final int TYPE_PACKAGE_YXHDXHRW = 1004; //1003,与businessauthconfig保持一致

    public static final int LOCALIZED_LOCALIZED = 1;
    public static final int LOCALIZED_UNIFIED = 0;
    /**
     *
     * @param business 类型，资费小类为0
     * @param business_id 资费小类id
     * @return
     */
    public List<LocalizedConfig> findByBusinessAndId(int business, String business_id) {
        return dao.find("SELECT * FROM localized_config WHERE business=? AND business_id=?",business,business_id);
    }

    /**
     * 更新业务授权信息
     * @param business_id
     * @param localized_exist 原来的属性
     * @param is_localized
     * @param cityIds
     */
    public void deleteAuthConfig(int business,int business_id,int localized_exist, int is_localized, Integer[] cityIds){
        deleteAuthConfig(Constant.Table.TABLE_BUSINESS_AUTH_CONFIG,business,business_id,localized_exist,is_localized,cityIds);
        deleteAuthConfig(Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG,business,business_id,localized_exist,is_localized,cityIds);
    }

    /**
     * 删除某张表的授权数据，目前就业务授权和泛店员业务授权
     * @param tableName
     * @param business
     * @param business_id
     * @param localized_exist
     * @param is_localized
     * @param cityIds
     */
    public void deleteAuthConfig(String tableName,int business,int business_id,int localized_exist, int is_localized, Integer[] cityIds){
        if(LOCALIZED_UNIFIED == localized_exist && is_localized==LOCALIZED_UNIFIED){//原来统一，现在统一
            //什么都不干
        }else if(localized_exist != is_localized){//原来是属地化，现在统一 或者 原来统一，现在属地化
            deleteByBusi(tableName,business,business_id);
        }else if(LOCALIZED_LOCALIZED == localized_exist && is_localized==LOCALIZED_LOCALIZED){//原来是属地化,现在也是属地化
            //删除没有的地市配置数据
            String sql = buildDeleteSQL(tableName,cityIds,business,business_id);//删除业务配置
            Db.update(sql);
            /*//1.找出已经被属地化的地市
            List<Record> records = Db.find("SELECT bac.city_org_id FROM business_auth_config bac WHERE bac.config_type=6 AND bac.config_business=0 AND bac.config_business_id=?",type_id);
            //2.删除没有的
            List<Integer> citysToDelete = new ArrayList<>();
            if(null!=records){
                for(Record record:records){
                    int city_org_id = record.getInt("city_org_id");
                    boolean in = false;
                    for(int city:cityIds){
                        if(city==city_org_id){
                            in = true;//原来的还在
                            break;
                        }
                    }
                    if(!in){//没在现在的地市列表中
                        citysToDelete.add(city_org_id);
                    }
                }
                //删除citysToDelete
            }*/
        }
    }

    private String buildDeleteSQL(String tableName,Integer[] cityIds,int business,int business_id) {
        StringBuilder builder = new StringBuilder("DELETE FROM ").append(tableName)
                .append(" WHERE config_business_id=").append(business_id)
                .append(" AND creator_org_id <> ");//属地化的create_org_id不等于现在的，都要删除
        for (int i=0;i<cityIds.length;i++){
            if(i == cityIds.length-1){
                builder.append(cityIds[i]);
            }else {
                builder.append(cityIds[i]).append(" AND creator_org_id <>");
            }
        }
        //资费类的比较特殊，可能存在多个活动，授权中小于1000
        if(business < 1000){
            builder.append(" AND config_business<1000");
        }else {
            builder.append(" AND config_business=").append(business);
        }
        return builder.toString();
    }
    /**
     * 更新属地化配置信息
     * @param business
     * @param business_id
     * @param is_localized
     * @param cityIds
     */
    public void localizedConfig(int business, int business_id, int is_localized, Integer[] cityIds) {
        //1. 首先删除原有数据
        deleteLocalizedConfig(business,business_id);
        //2. 添加现在的数据
        String sql = "INSERT INTO localized_config(business,business_id,localized_city_id) VALUES (?,?,?)";
        if(LOCALIZED_LOCALIZED == is_localized){//属地化授权
            if(null != cityIds && cityIds.length>0){
                for (Integer cityId:cityIds) {
                    Db.update(sql,business,business_id,cityId);
                }
            }else {
                throw  new RuntimeException("没有选择属地化地市");
            }
        }
    }
    public void deleteLocalizedConfig(int business, int business_id){
        Db.update("DELETE FROM localized_config WHERE business=? AND business_id=?",business,business_id);
    }
    public void deleteAuthConfig(String tableName,int business, Integer[] business_ids){
        if(null==business_ids || business_ids.length==0){
            return;
        }
        /*StringBuilder builder = new StringBuilder("DELETE FROM ").append(tableName)
                .append(" WHERE config_business=").append(business).append(" AND config_business_id=");
        List<String> sqlList = new ArrayList<>(business_ids.length);
        for (Integer id:business_ids){
            sqlList.add(builder.append(id).append(";").toString());
        }
        Db.batch(sqlList,business_ids.length);*/
        for (Integer id:business_ids){
            deleteByBusi(tableName,business,id);
        }
    }
    private void deleteByBusi(String tableName,int business,int business_id){
        //StringBuilder builder = new StringBuilder("DELETE FROM ").append(tableName).append(" WHERE config_business=").append(business).append(" AND config_business_id=").append(business_id);
        StringBuilder builder = new StringBuilder("DELETE FROM ").append(tableName).append(" WHERE config_business_id=").append(business_id);//一个资费小类属于不同的活动类型
        //资费类的比较特殊，可能存在多个活动，授权中小于1000
        if(business < 1000){
            builder.append(" AND config_business<1000");
        }else {
            builder.append(" AND config_business=").append(business);
        }
        Db.update(builder.toString());
    }
}
